import os, sys, zipfile, urllib
from copy import copy

from BeautifulSoup import BeautifulSoup

class PluginManager(object):
    
    def __init__(self, py):
        self.pytv = py
        self.search_for_plugins()
            
    def search_for_plugins(self):
        if not os.path.isdir(self.pytv.pluginFolder):
            os.makedirs(self.pytv.pluginFolder)
        self._plugins = {}
        
        plugs = os.listdir(self.pytv.pluginFolder)
        plugs = [p.replace('.py', '') for p in plugs if p.endswith('.py')]
        
        self._plugsList = self.pytv.db.restore_plugins()
        
        for plug in plugs:
            self._load_plugin(plug)

    def _load_plugin(self, plug):
        names = [n[0] for n in self._plugsList]
        old_syspath = copy(sys.path)
        try:
            sys.path += [self.pytv.pluginFolder]
            module = __import__(plug, globals(), locals(), ['plugin'])
            instance = module.Plugin()
            instance.configure(self.pytv.db, self.pytv.notif, self.pytv.pluginFolder)
            instance._active = False
            if instance._name not in names:
                self.pytv.db.save_plugin(instance._name)
            else:
                index = names.index(instance._name)
                if self._plugsList[index][1] == 1:
                    instance._active = True
            self._plugins[instance._name] = instance
        except(ImportError, AttributeError), reason:
            print 'error loading "%s": %s' % (plug, reason)
        finally:
            sys.path = old_syspath
            
    def get_plugins(self):
        plugs = [self._plugins[name] for name in self._plugins.keys()]
        return plugs
        
    def get_active_show_plugins(self):
        plugs = []
        for name in self._plugins.keys():
            if self._plugins[name]._active and self._plugins[name]._toShow:
                plug = [self._plugins[name]._icon, name]
                plugs.append(plug)
        return plugs
            
    def show(self, plugName):
        try:
            return self._plugins[plugName].show()
        except AttributeError, reason:
            print 'error loading "%s": %s' % (plugName, reason)

    def thread_plugins(self, db, notif, folder):
        try:
            for plug in self._plugins.values():
                if plug._toThread and plug._active:
                    print 'plugin: ' + plug._name
                    plug.configure(db, notif, folder)
                    plug.threadMe()
        except AttributeError, reason:
            print reason
            
def download_descriptor():
    plugins_list = []
    descriptor = urllib.urlopen('http://plugin.pytv-series.googlecode.com/hg/plugins.xml')
    soup = BeautifulSoup(descriptor.read())
    plugins = soup.findAll('plugin')
    for p in plugins:
        name = p.find('name').next
        description = p.find('description').next
        file = p.find('file').next
        plugins_list.append([name, description, file])
    return plugins_list

def download_plugin(file, folder):
    fileName = folder + os.path.basename(file)
    content = urllib.urlopen(file)
    f = open(fileName, 'w')
    f.write(content.read())
    f.close()
    zip = zipfile.ZipFile(fileName, 'r')
    zip.extractall(folder)
    os.remove(fileName)
